<template>
  <div class="flex flex-col h-full p-4 relative">
    <!-- 返回按钮与标题 - 悬浮在页面组件顶部 -->
    <div class="absolute top-0 left-0 right-0 bg-white z-10  py-4 px-6 flex items-center mb-6">
      <el-button @click="goBack" class="mr-2" text>
        <el-icon class="mr-1 w-6 h-6 text-black"><ArrowLeft /></el-icon>
      </el-button>
      <h2 class="text-xl font-bold">Warning Details</h2>
    </div>

    <div class="mt-16 flex flex-col space-y-6">
      <!-- 预警基本信息卡片 -->
      <div class="bg-white rounded-lg shadow p-6">
        <h3 class="text-lg font-bold pb-4">Warning Information</h3>
        <table class="w-full border-collapse">
          <tbody>
            <tr>
              <td class="border p-4 w-1/3">
                <span class="text-gray-500">Battery pack SN:</span>
                <span class="ml-2">{{
                  warningDetail?.batteryPackSN || "-"
                }}</span>
              </td>
              <td class="border p-4 w-1/3">
                <span class="text-gray-500">Device SN:</span>
                <span class="ml-2">{{ warningDetail?.deviceSN || "-" }}</span>
              </td>
              <td class="border p-4 w-1/3">
                <span class="text-gray-500">Alert name:</span>
                <span class="ml-2">{{
                  warningDetail?.alertName?.replace(
                    /textextextextextextextextextextextttt$/,
                    ""
                  ) || "-"
                }}</span>
              </td>
            </tr>
            <tr>
              <td class="border p-4">
                <span class="text-gray-500">Battery type:</span>
                <span class="ml-2">{{
                  warningDetail?.batteryType || "-"
                }}</span>
              </td>
              <td class="border p-4">
                <span class="text-gray-500">Capacity (kWh):</span>
                <span class="ml-2">{{ warningDetail?.capacity || "-" }}</span>
              </td>
              <td class="border p-4">
                <span class="text-gray-500 mr-1">Warning status:</span>
                <span class="ml-2 inline-flex gap-1 items-center">
                  <span class="w-2 h-2 rounded-full" :class="warningDetail?.status === 'Open'
                    ? 'bg-red-500'
                    : 'bg-green-500'
                    "></span>
                  {{ warningDetail?.status === "Open" ? "Open" : "Close" }}
                </span>
              </td>
            </tr>
            <tr>
              <td class="border p-4">
                <div class="flex items-center">
                  <span class="text-gray-500">Occurrence time:</span>
                  <el-tooltip class="ml-1" effect="dark" content="The time when this warning occurred in the device"
                    placement="top">
                    <Warning class="cursor-help text-gray-400 w-4 h-4" />
                  </el-tooltip>
                  <span class="ml-2">{{
                    warningDetail?.predictedTime || "-"
                  }}</span>
                </div>
              </td>
              <td class="border p-4">
                <div class="flex items-center">
                  <span class="text-gray-500">Detect time:</span>
                  <el-tooltip class="ml-1" effect="dark" content="The time when this warning is identified/detected"
                    placement="top">
                    <Warning class="cursor-help text-gray-400 w-4 h-4" />
                  </el-tooltip>
                  <span class="ml-2">{{
                    warningDetail?.detectTime || "-"
                  }}</span>
                </div>
              </td>
              <td class="border p-4"></td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 历史数据卡片 -->
      <div class="bg-white rounded-lg shadow p-6 flex-1 overflow-y-auto">
        <h3 class="text-lg font-bold mb-4">
          Historical Data
        </h3>

        <!-- 图表区域 -->
        <div class="grid grid-cols-1 gap-6">
          <!-- 最大/最小电池电压图表 -->
          <div class="border rounded p-4">
            <h4 class="text-base font-bold mb-4">
              Max/Min Cell Voltage
            </h4>
            <div ref="maxMinChartRef" style="height: 300px" class="chart"></div>
          </div>

          <!-- 电池组总电压图表 -->
          <div class="border rounded p-4">
            <h4 class="text-base font-bold mb-4">
              Total Voltage
            </h4>
            <div ref="totalVoltageChartRef" style="height: 300px" class="chart"></div>
          </div>

          <!-- 电池组总电流图表 -->
          <div class="border rounded p-4">
            <h4 class="text-base font-bold mb-4">
              Total Current
            </h4>
            <div ref="totalCurrentChartRef" style="height: 300px" class="chart"></div>
          </div>

          <!-- 电池组温度图表 -->
          <div class="border rounded p-4">
            <h4 class="text-base font-bold mb-4">
              Battery Pack Temperature
            </h4>
            <div ref="temperatureChartRef" style="height: 300px" class="chart"></div>
          </div>

          <!-- 电池组SOC图表 -->
          <div class="border rounded p-4">
            <h4 class="text-base font-bold mb-4">SOC</h4>
            <div ref="socChartRef" style="height: 300px" class="chart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, onBeforeUnmount, nextTick } from "vue";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from "echarts/components";
import { ArrowLeft, Warning } from "@element-plus/icons-vue";
import { CanvasRenderer } from "echarts/renderers";
import type { EarlyWarningItem } from "../data";
import { bmsApi } from "@/api/bms";
import { ElMessage } from "element-plus";

// 定义 props
interface Props {
  warningId: string;
}

const props = defineProps<Props>();

// 定义 emits
const emit = defineEmits<{
  'go-back': [];
}>();

// 注册必须的组件
echarts.use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
]);

// 图表DOM引用
const maxMinChartRef = ref<HTMLElement | null>(null);
const totalVoltageChartRef = ref<HTMLElement | null>(null);
const totalCurrentChartRef = ref<HTMLElement | null>(null);
const temperatureChartRef = ref<HTMLElement | null>(null);
const socChartRef = ref<HTMLElement | null>(null);

// echarts实例
let maxMinChart: echarts.ECharts | null = null;
let totalVoltageChart: echarts.ECharts | null = null;
let totalCurrentChart: echarts.ECharts | null = null;
let temperatureChart: echarts.ECharts | null = null;
let socChart: echarts.ECharts | null = null;

// 获取预警详情
const warningDetail = ref<EarlyWarningItem | null>(null);

// 共用时间轴数据
const hours = [
  "02:00",
  "06:00",
  "08:00",
  "10:00",
  "12:00",
  "14:00",
  "16:00",
  "18:00",
  "20:00",
  "20:00",
  "22:00",
  "24:00"
];

// ========== 电池电压数据 ==========
// 最大电池电压数据 - 单位: V
const maxVoltageData = [
  0.8, 1.2, 1.5, 0.9, 2.2, 3.1, 2.8, 3.0, 1.8, 1.9, 2.2, 2.1
];

// 最小电池电压数据 - 单位: V
const minVoltageData = [
  0.0, 0.0, 0.3, 1.6, 1.7, 0.9, 0.8, 1.2, 1.5, 1.2, 0.9, 0.0
];

// ========== 电池组总电压数据 ==========
// 电池组总电压数据 - 单位: V
const totalVoltageData = [
  1.2, 0.0, 0.5, 0.7, 1.5, 2.0, 3.0, 3.5, 3.0, 2.8, 1.8, 3.0
];

// ========== 电池组电流数据 ==========
// 电池组总电流数据 - 单位: A
const totalCurrentData = [
  1.0, 0.2, 0.5, 0.3, 1.5, 2.8, 3.0, 3.2, 3.5, 2.5, 2.0, 3.0
];

// ========== 电池组温度数据 ==========
// 电池组温度数据 - 单位: °C
const temperatureData = [
  1.1, 0.0, 0.6, 0.2, 1.5, 3.0, 3.0, 2.8, 3.2, 2.5, 1.9, 3.0
];

// ========== 电池组SOC数据 ==========
// 电池荷电状态(State of Charge)数据 - 单位: %
const socData = [1.0, 0.0, 0.5, 0.2, 1.5, 3.0, 3.0, 3.5, 2.8, 3.0, 2.0, 3.0];

// ========== 图表配置函数 ==========

// 最大/最小电压图表配置
const getMaxMinVoltageOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["Max Cell Voltage", "Min Cell Voltage"]
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(V)"
    },
    series: [
      {
        name: "Max Cell Voltage",
        type: "line",
        data: maxVoltageData,
        itemStyle: {
          color: "#67C23A"
        },
        areaStyle: {
          opacity: 0.3,
          color: "#67C23A"
        }
      },
      {
        name: "Min Cell Voltage",
        type: "line",
        data: minVoltageData,
        itemStyle: {
          color: "#409EFF"
        },
        areaStyle: {
          opacity: 0.3,
          color: "#409EFF"
        }
      }
    ]
  };
};

// 电池组总电压图表配置
const getTotalVoltageOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(V)"
    },
    series: [
      {
        type: "line",
        data: totalVoltageData,
        itemStyle: {
          color: "#E6A23C"
        },
        areaStyle: {
          opacity: 0.3,
          color: "#E6A23C"
        }
      }
    ]
  };
};

// 电池组总电流图表配置
const getTotalCurrentOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(A)" // 电流单位
    },
    series: [
      {
        type: "line",
        data: totalCurrentData,
        itemStyle: {
          color: "#409EFF" // 蓝色
        },
        areaStyle: {
          opacity: 0.3,
          color: "#409EFF"
        }
      }
    ]
  };
};

// 电池组温度图表配置
const getTemperatureOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(°C)" // 温度单位
    },
    series: [
      {
        type: "line",
        data: temperatureData,
        itemStyle: {
          color: "#E6A23C" // 橙色
        },
        areaStyle: {
          opacity: 0.3,
          color: "#E6A23C"
        }
      }
    ]
  };
};

// 电池组SOC图表配置
const getSocOption = () => {
  return {
    tooltip: {
      trigger: "axis"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value",
      name: "(%)" // SOC单位
    },
    series: [
      {
        type: "line",
        data: socData,
        itemStyle: {
          color: "#6366F1" // 紫色
        },
        areaStyle: {
          opacity: 0.3,
          color: "#6366F1"
        }
      }
    ]
  };
};

// 初始化图表
const initCharts = () => {
  // 初始化最大/最小电压图表
  if (maxMinChartRef.value && !maxMinChart) {
    maxMinChart = echarts.init(maxMinChartRef.value);
    maxMinChart.setOption(getMaxMinVoltageOption());
  }

  // 初始化总电压图表
  if (totalVoltageChartRef.value && !totalVoltageChart) {
    totalVoltageChart = echarts.init(totalVoltageChartRef.value);
    totalVoltageChart.setOption(getTotalVoltageOption());
  }

  // 初始化总电流图表
  if (totalCurrentChartRef.value && !totalCurrentChart) {
    totalCurrentChart = echarts.init(totalCurrentChartRef.value);
    totalCurrentChart.setOption(getTotalCurrentOption());
  }

  // 初始化温度图表
  if (temperatureChartRef.value && !temperatureChart) {
    temperatureChart = echarts.init(temperatureChartRef.value);
    temperatureChart.setOption(getTemperatureOption());
  }

  // 初始化SOC图表
  if (socChartRef.value && !socChart) {
    socChart = echarts.init(socChartRef.value);
    socChart.setOption(getSocOption());
  }
};

// 处理窗口大小变化
const handleResize = () => {
  // 自适应调整所有图表大小
  maxMinChart?.resize();
  totalVoltageChart?.resize();
  totalCurrentChart?.resize();
  temperatureChart?.resize();
  socChart?.resize();
};

// 加载预警详情数据
onMounted(async () => {
  try {
    const res = await bmsApi.getEarlyWarningDetail({ faultId: props.warningId });
    if (res.code === 0) {
      const d = res.data || {};
      warningDetail.value = {
        id: String(d.id ?? ""),
        batteryPackSN: d.batteryPackSn ?? "",
        deviceSN: d.deviceSn ?? "",
        alertName: d.alertName ?? "",
        batteryType: d.batteryType ?? "",
        capacity: Number(d.capacity ?? 0),
        predictedTime: d.predictedTime ?? "",
        detectTime: d.detectTime ?? "",
        status: (String(d.status).toLowerCase() === 'open' || d.status === 0 ? 'Open' : 'Close')
      } as EarlyWarningItem;
    } else {
      throw new Error(res.msg || '获取预警详情失败');
    }
  } catch (e: any) {
    ElMessage.error(e.message || '网络错误');
  }

  // 初始化图表
  nextTick(() => {
    initCharts();
    window.addEventListener("resize", handleResize);
  });
});

// 销毁图表实例
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);

  // 释放图表实例资源
  maxMinChart?.dispose();
  maxMinChart = null;

  totalVoltageChart?.dispose();
  totalVoltageChart = null;

  totalCurrentChart?.dispose();
  totalCurrentChart = null;

  temperatureChart?.dispose();
  temperatureChart = null;

  socChart?.dispose();
  socChart = null;
});

// 返回上一页
const goBack = () => {
  emit('go-back');
};
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
